﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YunRuiFarm.Models;
using static YunRuiFarm.Models.DatabaseModels;

namespace YunRuiFarm.Controllers
{
    public class YunRuiFarmAPIController : Controller
    {
        // GET: YunRuiFarmAPI
        /// <summary>
        /// 验证用户名密码
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="PassWord"></param>
        /// <returns>产生的token</returns>
        public ActionResult LoginAPI(String UserName, String PassWord)
        {
            var list = user_info.Find(p => p.Username == UserName && p.Password == PassWord);
            if (list.Count == 0)
            {
                return Json(ResultHelper.GetErrorModel("用户名密码错误")); //用户名与密码不匹配
            }
            else
            {
                string token = System.Guid.NewGuid().ToString("N");
                var PersonId = user_info.Find(p => p.Username == UserName);
                var Record = user_token.Find(p => p.PersonId == PersonId[0].Id);
                if(Record.Count==0)
                {
                    var u = new user_token { PersonId = PersonId[0].Id, Token = token, Createtime = DateTime.Now, Expirytime = DateTime.Now.AddDays(1) };
                    u.Save();
                }
                else
                {
                    Record[0].Token = token;
                    Record[0].Createtime = DateTime.Now;
                    Record[0].Expirytime = DateTime.Now.AddHours(1);
                    Record[0].Save();
                }
                //如果token已存在时再次登陆，将数据库中的token更新
                return Json(ResultHelper.GetSuccessModel(token), JsonRequestBehavior.AllowGet);//用户名与密码匹配
            }
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="Sex"></param>
        /// <param name="Contacts"></param>
        /// <param name="UserName"></param>
        /// <param name="PassWord"></param>
        /// <returns></returns>
        public ActionResult RegisterAPI(string Name, int Sex, string Contacts, String UserName, String PassWord)
        {
            var result = user_info.Find(p => p.Username == UserName);
            if (result.Count == 0)
            {
                var u = new user_info { Name = Name, Sex = Sex, Contacts = Contacts, Power = 1, Username = UserName, Password = PassWord, Createtime = DateTime.Now, Updatetime = DateTime.Now };
                u.Save();
                result = user_info.Find(p => p.Username == UserName);
                if (result.Count != 0)
                    return Json(ResultHelper.RegisterSuccessModel("注册成功！正在跳转到登录页面…"));
                else
                    return Json(ResultHelper.RegisterErrorModel("注册失败！"));
            }
            else
            {
                return Json(ResultHelper.RegisterErrorModel("该用户名已被注册！"));
            }
        }
        /// <summary>
        /// 验证登录权限,获取用户姓名
        /// </summary>
        /// <param name="Token"></param>
        /// <returns>用户名</returns>
        public ActionResult GetLoginMessageAPI(string Token)
        {
            if(Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var userinfo = user_info.FindById(PersonId);
                return Json(ResultHelper.GetIndexMessageModel(userinfo.Name));
            }
            else
            return Json(ResultHelper.GetIndexMessageErrorModel("未获取到token"));//未获取到token
        }
        public ActionResult IndexGetMessageAPI(string Token)
        {
            var list = web_info.Find(p=>p.Place== "首页轮播图");
            return Json(ResultHelper.GetIndexMessageModel(list,list.Count));//未获取到token
        }
        /// <summary>
        /// 获取个人信息
        /// </summary>
        /// <param name="Token"></param>
        /// <returns>个人信息</returns>
        public ActionResult UserInfoGetMessageAPI(string Token)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var userinfo = user_info.FindById(PersonId);
                return Json(ResultHelper.GetUserInfoModel(userinfo.Name, userinfo.Sex, userinfo.Contacts, userinfo.Username, userinfo.Password));
            }
            else
                return Json(ResultHelper.GetIndexMessageErrorModel("未获取到token"));//未获取到token

        }
        /// <summary>
        /// 用户编辑后保存个人信息
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="Name"></param>
        /// <param name="Sex"></param>
        /// <param name="Contacts"></param>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public ActionResult UserInfoSaveMessageAPI(string Token, string Name, int Sex, string Contacts, string Username, string Password)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var userinfo = user_info.FindById(PersonId);
                userinfo.Name = Name;
                userinfo.Sex = Sex;
                userinfo.Contacts = Contacts;
                userinfo.Username = Username;
                userinfo.Password = Password;
                userinfo.Save();
                userinfo = user_info.FindById(PersonId);
                return Json(ResultHelper.GetUserInfoModel(userinfo.Name, userinfo.Sex, userinfo.Contacts, userinfo.Username, userinfo.Password));
            }
            else
                return Json(ResultHelper.GetIndexMessageErrorModel("未获取到token"));//未获取到token

        }
        /// <summary>
        /// 羊信息页面获取登录人姓名
        /// </summary>
        /// <param name="Token"></param>
        /// <returns></returns>
        //public ActionResult AdoptGetLoginMessageAPI(string Token)
        //{
        //    if (Verification(Token))
        //    {
        //        var tokenlist = user_token.Find(p => p.Token == Token);
        //        long PersonId = tokenlist[0].PersonId;
        //        var userinfo = user_info.FindById(PersonId);
        //        return Json(ResultHelper.GetLoginMessageSuccessModel(userinfo.Name));
        //    }
        //    else
        //        return Json(ResultHelper.GetLoginMessageErrorModel("未获取到token"));//未获取到token
        //}
        /// <summary>
        /// 获取羊信息页面内容
        /// </summary>
        /// <returns></returns>
        public ActionResult AdoptGetMessageAPI()
        {
            var info = goat_info.FindBySql("select * from goat_info");
            if(info.Count==0)
                return Json(ResultHelper.GetErrorModel("未找到羊信息"));
            else
            {
                var Kind1 = "羊信息轮播图";
                var Kind2 = "羊信息介绍图";
                var CarouselFigure = web_info.Find(p => p.Place == Kind1);
                var Introduction=web_info.Find(p => p.Place == Kind2);
                return Json(ResultHelper.GetAdoptMessageModel(CarouselFigure, Introduction, CarouselFigure.Count, info[0].Kind, info[0].Number, info[1].Kind, info[1].Number));
            }
        }
        /// <summary>
        /// 羊领养页面获取羊信息
        /// </summary>
        /// <param name="Kind"></param>
        /// <returns></returns>
        public ActionResult AdoptGoatGetMessageAPI(string Kind)
        {
            long Id = long.Parse(Kind);
            var info = goat_info.FindById(Id);
            var list1 = web_info.Find(p => p.Place == "山羊轮播图");
            var list2 = web_info.Find(p => p.Place == "湖羊轮播图");
            return Json(ResultHelper.GetAdoptGoatMessageModel(list1,list2,info.Kind, info.Number,info.Introduce));
        }
        /// <summary>
        /// 羊领养预约时获取用户信息
        /// </summary>
        /// <param name="Token"></param>
        /// <returns></returns>
        public ActionResult GoatAppointmentGetLoginMessageAPI(string Token)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var userinfo = user_info.FindById(PersonId);
                return Json(ResultHelper.GetGoatAppointmentSuccessModel(userinfo.Name,userinfo.Contacts));
            }
            else
                return Json(ResultHelper.GetGoatAppointmentErrorModel());//未获取到token
        }
        /// <summary>
        /// 对羊下订单
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="Name"></param>
        /// <param name="Contacts"></param>
        /// <param name="Kind"></param>
        /// <param name="Number"></param>
        /// <returns></returns>
        public ActionResult GoatAppointmentAPI(string Token,string Name,string Contacts, int Kind,int Number)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                string kind;
                if (Kind == 1)
                    kind = "山羊";
                else if (Kind == 2)
                    kind = "湖羊";
                else
                    return Json(ResultHelper.GetErrorModel("请先选择领养的种类。"));
                var OrderId = "YunRuiGoat" + DateTime.Now.ToString("yyyyMMddHHmmss"); //产生订单号
                var OrderIdList = goat_adopt.Find(p => p.OrderId == OrderId);
                if(OrderIdList.Count>0)
                    return Json(ResultHelper.GetErrorModel("订单号产生失败，请重试。"));
                var goatadopt = new goat_adopt { PersonID = PersonId,OrderId=OrderId, Name=Name,Contacts= Contacts, Kind = kind, Number = Number, Result = "预约中", Createtime = DateTime.Now,Updatetime=DateTime.Now };
                goatadopt.Save();
                return Json(ResultHelper.GetSuccessModel("预约成功，请等待商家处理。"));
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));//未获取到token
        }
        /// <summary>
        /// 获取用户的羊领养预约信息
        /// </summary>
        /// <param name="Token"></param>
        /// <returns></returns>
        public ActionResult UserGoatOrderGetMessageAPI(string Token,int page,int limit)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var count = goat_adopt.Find(p => p.PersonID == PersonId).Count;
                var start = (page - 1) * limit;
                var sql = "select * from goat_adopt where PersonId=" + PersonId + " Order By Result DESC,Createtime DESC limit " + start+","+limit;
                var OrderList = goat_adopt.FindBySql(sql);
                return Json(ResultHelper.GetGoatOrderMessageModel(OrderList, count), JsonRequestBehavior.AllowGet);      
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));//未获取到token
        }
        /// <summary>
        /// 取消用户羊领养预约订单
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="Token"></param>
        /// <returns></returns>
        public ActionResult GoatOrderUnsubscribeAPI(string OrderId,string Token)
        {
            if (Verification(Token))
            {
                var Unsubscribelist = goat_adopt.Find(p => p.OrderId == OrderId&&p.Result == "预约中");
                if (Unsubscribelist.Count == 0)
                    return Json(ResultHelper.GetErrorModel("未找到该订单"));
                else
                {
                    Unsubscribelist[0].Result = "已退订";
                    Unsubscribelist[0].Save();
                    return Json(ResultHelper.GetSuccessModel("已成功退订"));
                }
                   
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));
        }
        /// <summary>
        /// 获取订单对应的羊信息
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="Token"></param>
        /// <returns></returns>
        public ActionResult GoatOrderDetailGetMessageAPI(string Token, int page, int limit)
        {
            if (Verification(Token))
            {
                var user= user_token.Find(p => p.Token == Token);
                var adoptlist = goat_adopt.FindBySql("select * from user_adoptinfo INNER JOIN goat_adopt on user_adoptinfo.OrderId = goat_adopt.OrderId where PersonId = " + user[0].PersonId);
                var start = (page - 1) * limit;
                var sql = "select * from user_adoptinfo INNER JOIN goat_adopt on user_adoptinfo.OrderId = goat_adopt.OrderId where PersonId = " + user[0].PersonId + " Order By user_adoptinfo.Updatetime DESC limit " + start + "," + limit;
                var dataillist = user_adoptinfo.FindBySql(sql);
                return Json(ResultHelper.GoatOrderDetailSuccessrModel(dataillist, adoptlist.Count), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GoatOrderDetailErrorModel("未获取到token"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult AgriculturalGetMessageAPI()
        {
            var list = product_info.FindBySql("select * from product_info where Id!=0 ORDER BY Sort DESC");
            var CarouselFigure = web_info.Find(p=>p.Place== "农副产品轮播图");
            return Json(ResultHelper.AgriculturalMessageModel(list, CarouselFigure, list.Count), JsonRequestBehavior.AllowGet);
        }
        public ActionResult AgriculturalDetailGetMessageAPI(long Id)
        {
            var list = product_info.FindById(Id);
            return Json(list,JsonRequestBehavior.AllowGet);
        }
        public ActionResult AgriculturalAdoptAPI(long Id,double Price,int Number, double Total,string Token,string Name, string Contacts,int Style)
        {
            
            if (Verification(Token))
            {
                var AgriculturalID = product_info.Find(p => p.Id == Id);
                if(AgriculturalID.Count==0)
                    return Json(ResultHelper.GetErrorModel("不存在该商品"), JsonRequestBehavior.AllowGet);
                if (AgriculturalID[0].Price!=Price)
                    return Json(ResultHelper.GetErrorModel("商品价格有误"), JsonRequestBehavior.AllowGet);
                if (int.Parse(AgriculturalID[0].Total) <Number)
                    return Json(ResultHelper.GetErrorModel("商品剩余数量不足"), JsonRequestBehavior.AllowGet);
                if (int.Parse(AgriculturalID[0].Total) < 1)
                    return Json(ResultHelper.GetErrorModel("商品数量不正确"), JsonRequestBehavior.AllowGet);
                if (Style==0&&Price * Number != Total)
                    return Json(ResultHelper.GetErrorModel("总金额计算有误"), JsonRequestBehavior.AllowGet);
                var list = product_info.FindById(Id);
                if(Style == 0 && (list.Price != Price || Total != list.Price * Number))
                    return Json(ResultHelper.GetErrorModel("总金额计算有误"), JsonRequestBehavior.AllowGet);
                var PersonId = user_token.Find(p => p.Token == Token)[0].PersonId;
                if (Style == 1)
                    Total = 0;
                var OrderId = "YunRuiAgricultural" + DateTime.Now.ToString("yyyyMMddHHmmss"); //产生订单号
                var OrderIdList = product_order.Find(p => p.OrderId == OrderId);
                if (OrderIdList.Count > 0)
                    return Json(ResultHelper.GetErrorModel("订单号产生失败，请重试。"));
                var Order = new product_order {
                    OrderId= OrderId,
                    PersonID =PersonId,
                    AgriculturalID =Id,
                    Name =Name,
                    Contacts =Contacts,
                    Number=Number,
                    Price =Total,
                    Result ="预订中",
                    Time =DateTime.Now.AddDays(list.Time),
                    Remarks="",
                    Createtime=DateTime.Now,
                    Updatetime=DateTime.Now,
                    Style=Style
                };
                Order.Save();
                return Json(ResultHelper.GetSuccessModel("预订成功"), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult AgriculturalOrderUnsubscribeAPI(string OrderId, string Token)
        {
            if (Verification(Token))
            {
                var Unsubscribelist = product_order.Find(p => p.OrderId == OrderId && p.Result == "预订中");
                if (Unsubscribelist.Count == 0)
                    return Json(ResultHelper.GetErrorModel("未找到该订单"));
                else
                {
                    Unsubscribelist[0].Result = "已退订";
                    Unsubscribelist[0].Save();
                    return Json(ResultHelper.GetSuccessModel("已成功退订"));
                }

            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));
        }
        public ActionResult UserAgriculturalOrderGetMessageAPI(string Token,int page,int limit)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var count = product_order.Find(p => p.PersonID == PersonId).Count;
                var start = (page - 1) * limit;
                var sql = "select * from product_order where PersonId="+ PersonId + " Order By Result DESC limit "+start+","+limit;
                var OrderList = product_order.FindBySql(sql);
                return Json(ResultHelper.GetAgriculturalOrderMessageModel(OrderList, count), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));//未获取到token
        }
        
        /// <summary>
        /// 取消用户羊领养预约订单
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="Token"></param>
        /// <returns></returns>
        public ActionResult GoatAgriculturalUnsubscribeAPI(string OrderId, string Token)
        {
            if (Verification(Token))
            {
                var Unsubscribelist = goat_adopt.Find(p => p.OrderId == OrderId && p.Result == "预约中");
                if (Unsubscribelist.Count == 0)
                    return Json(ResultHelper.GetErrorModel("未找到该订单"));
                else
                {
                    Unsubscribelist[0].Result = "已退订";
                    Unsubscribelist[0].Save();
                    return Json(ResultHelper.GetSuccessModel("已成功退订"));
                }

            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));
        }

        public ActionResult GetRestaurantMessageAPI(string NowTime)
        {
            
            var received = cater_order.Find(p=>p.Date== NowTime);
            return Json(ResultHelper.GoatRestaurantMessageSuccessModel(received));
        }
        public ActionResult RestaurantAppointmentAPI(string name, string contacts,int number,string date,string time,string Private, string Activity, string Restaurant, string Token, string remarks)
        {
                
            if (Verification(Token))
            {
                
                var received = cater_order.Find(p => p.Date == date);
                var personnumber = 0;
                for(var i=0;i<received.Count;i++)
                {
                    if(received[i].Private==true && received[i].Result=="预约成功")
                        return Json(ResultHelper.GetErrorModel("抱歉，当日已被包场。"));
                    personnumber += received[i].Number;
                    if(personnumber>=20)
                        return Json(ResultHelper.GetErrorModel("抱歉，当日接待人数较多。"));
                }
                var PersonId = user_token.Find(p => p.Token == Token)[0].PersonId;
                var OrderId = "YunRuiAgricultural" + DateTime.Now.ToString("yyyyMMddHHmmss"); //产生订单号
                var OrderIdList = cater_detail.Find(p => p.OrderId == OrderId);
                if (OrderIdList.Count > 0)
                    return Json(ResultHelper.GetErrorModel("订单号产生失败，请重试。"));
                var Order = new cater_order
                {
                    OrderId = OrderId,
                    PersonID = PersonId,
                    Name=name,
                    Contacts= contacts,
                    Date = date,
                    Number=number,
                    Private= bool.Parse(Private), 
                    Result ="预约中",
                    Createtime=DateTime.Now,
                    Updatetime= DateTime.Now
                };
                
                var Detail = new cater_detail
                {
                    OrderId = OrderId,
                    Activity=Activity,
                    Restaurant= Restaurant,
                    Time=time,
                    Remarks= remarks,
                    Createtime=DateTime.Now,
                    Updatetime = DateTime.Now
                };
                Order.Save();
                Detail.Save();
                return Json(ResultHelper.GetSuccessModel("预约成功"), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult UserRestaurantOrderGetMessageAPI(string Token, int page, int limit)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var count = cater_order.Find(p => p.PersonID == PersonId).Count;
                var start = (page - 1) * limit;
                var sql = "select * from cater_order where PersonID = " + PersonId + " Order By Result DESC limit " + start + "," + limit;
                var OrderList = cater_order.FindBySql(sql);
                return Json(ResultHelper.GetUserRestaurantOrderMessageModel(OrderList, count), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));//未获取到token
        }
        
        public ActionResult UserFeedbackAPI(string Message, string Token)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var Order = new user_feedback
                {
                    PersonId = PersonId,
                    Message = Message,
                    Answer = "",
                    Result = "未答复",
                    Createtime = DateTime.Now,
                    Updatetime = DateTime.Now
                };
                Order.Save();
                return Json(ResultHelper.GetSuccessModel("提交成功"), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult UserFeedbackGetMessageAPI(string Token, int page, int limit)
        {
            if (Verification(Token))
            {
                var count = user_feedback.FindBySql("select * from user_feedback").Count;
                var start = (page - 1) * limit;
                var sql = "select * from user_feedback Order By Result DESC,Createtime DESC limit " + start + "," + limit;
                var myFeedbackList = user_feedback.FindBySql(sql);
                return Json(ResultHelper.GetUserFeedbackMessageModel(myFeedbackList, count), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));//未获取到token
        }
        public ActionResult GetAdministratorsPower(string Token)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var sql = "select * from user_info where Id="+ PersonId;
                var power = user_info.FindBySql(sql)[0].Power;
                var url = "";
                if (power == 2)
                    url = "/YunRuiFarm/AdministratorsGoatOrder";
                return Json(ResultHelper.GetSuccessModel(url), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));//未获取到token
        }
        public ActionResult ManageGoatOrderGetMessageAPI(string Token, int page, int limit)
        {
            if (Verification(Token))
            {
                var count = goat_adopt.Find(p => p.Result != "已退订").Count;
                var start = (page - 1) * limit;
                var sql = "select * from goat_adopt where Result!='已退订' Order By Result,Createtime DESC limit " + start + "," + limit;
                var OrderList = goat_adopt.FindBySql(sql);
                return Json(ResultHelper.GetGoatOrderMessageModel(OrderList, count), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));//未获取到token
        }
        public ActionResult ManageGoatOrderAgreenAPI(string OrderId,int Number,string GoatId)
        {
            var goatid=GoatId.Split(',');
            for(var i=0;i<Number;i++)
            {
                var Order = new user_adoptinfo
                {
                    OrderId = OrderId,
                    GoatId = goatid[i],
                    Time = DateTime.Now,
                    Report = "",
                    Createtime = DateTime.Now,
                    Updatetime = DateTime.Now
                };
                Order.Save();
            }
            var OrderList = goat_adopt.FindBySql("select * from goat_adopt where OrderId='" + OrderId + "'")[0];
            OrderList.Number = Number;
            OrderList.Result = "预约成功";
            OrderList.Updatetime = DateTime.Now;
            OrderList.Save();
            return Json(ResultHelper.GetSuccessModel("预约成功"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult ManageGoatOrderDisagreeAPI(string OrderId)
        {
           
            var OrderList = goat_adopt.FindBySql("select * from goat_adopt where OrderId='" + OrderId + "'")[0];
            
            OrderList.Result = "预约失败";
            OrderList.Updatetime = DateTime.Now;
            OrderList.Save();
            return Json(ResultHelper.GetSuccessModel(""), JsonRequestBehavior.AllowGet);
        }
        public ActionResult ManageGoatOrderDetailGetMessageAPI(string Token, int page, int limit)
        {
            if (Verification(Token))
            {
                var count = user_adoptinfo.FindBySql("select * from user_adoptinfo").Count;
                var start = (page - 1) * limit;
                var sql = "select * from user_adoptinfo Order By Updatetime limit " + start + "," + limit;
                var dataillist = user_adoptinfo.FindBySql(sql);
                return Json(ResultHelper.GoatOrderDetailSuccessrModel(dataillist, count), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GoatOrderDetailErrorModel("未获取到token"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult ManageEditGoatOrderDetailAPI(string Message,long Id)
        {
            var OrderList = user_adoptinfo.FindById(Id);
            OrderList.Report = Message;
            OrderList.Updatetime = DateTime.Now;
            OrderList.Save();
            return Json(ResultHelper.GetSuccessModel("编辑成功"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult ManageRestaurantOrderGetMessageAPI(string Token, int page, int limit)
        {
            if (Verification(Token))
            {
                var tokenlist = user_token.Find(p => p.Token == Token);
                long PersonId = tokenlist[0].PersonId;
                var count = cater_order.Find(p => p.Id !=0).Count;
                var start = (page - 1) * limit;
                var sql = "select * from cater_order Order By Result limit " + start + "," + limit;
                var OrderList = cater_order.FindBySql(sql);
                return Json(ResultHelper.GetUserRestaurantOrderMessageModel(OrderList, count), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));//未获取到token
        }
        public ActionResult ManageAgreenRestaurantOrderDetailAPI(long Id)
        {
            var OrderList = cater_order.FindById(Id);
            OrderList.Result = "预约成功";
            OrderList.Updatetime = DateTime.Now;
            OrderList.Save();
            return Json(ResultHelper.GetSuccessModel("编辑成功"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult ManageDesagreenRestaurantOrderDetailAPI(long Id)
        {
            var OrderList = cater_order.FindById(Id);
            OrderList.Result = "预约失败";
            OrderList.Updatetime = DateTime.Now;
            OrderList.Save();
            return Json(ResultHelper.GetSuccessModel("编辑成功"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult ManageAgriculturalOrderGetMessageAPI(string Token, int page, int limit)
        {
            if (Verification(Token))
            {
                
                var count = product_order.Find(p => p.Id >= 0).Count;
                var start = (page - 1) * limit;
                var sql = "select * from product_order where Result!='已退订'  Order By Result limit " + start + "," + limit;
                var OrderList = product_order.FindBySql(sql);
                return Json(ResultHelper.GetAgriculturalOrderMessageModel(OrderList, count), JsonRequestBehavior.AllowGet);
            }
            else
                return Json(ResultHelper.GetErrorModel("未获取到token"));//未获取到token
        }
        public ActionResult ManageAgreenAgriculturalOrderDetailAPI(long Id,int Number)
        {
            var OrderList = product_order.FindById(Id);
            OrderList.Result = "预订成功";
            OrderList.Updatetime = DateTime.Now;
            OrderList.Save();
            var Orderinfo = product_info.FindById(OrderList.AgriculturalID);
            if(int.Parse(Orderinfo.Total) - Number<0)
                return Json(ResultHelper.GetErrorModel("剩余数量不足"), JsonRequestBehavior.AllowGet);
            Orderinfo.Total = (int.Parse(Orderinfo.Total) - Number).ToString();
            Orderinfo.Save();
            return Json(ResultHelper.GetSuccessModel("编辑成功"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult ManageDesagreenAgriculturalOrderDetailAPI(long Id)
        {
            var OrderList = product_order.FindById(Id);
            OrderList.Result = "预订失败";
            OrderList.Updatetime = DateTime.Now;
            OrderList.Save();
            return Json(ResultHelper.GetSuccessModel("编辑成功"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult ManageFeedbackGetMessageAPI(int page, int limit)
        {
            var count = user_feedback.FindBySql("select * from user_feedback").Count;
            var start = (page - 1) * limit;
            var sql = "select * from user_feedback Order By Result DESC,Createtime DESC limit " + start + "," + limit;
            var myFeedbackList = user_feedback.FindBySql(sql);
            return Json(ResultHelper.GetUserFeedbackMessageModel(myFeedbackList, count), JsonRequestBehavior.AllowGet);
        }
        public ActionResult ManageFeedbackEditAPI(long Id,string Message)
        {
            var FeedbackList = user_feedback.FindById(Id);
            FeedbackList.Result = "已答复";
            FeedbackList.Updatetime = DateTime.Now;
            FeedbackList.Answer = Message;
            FeedbackList.Save();
            return Json(ResultHelper.GetSuccessModel("编辑成功"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult AdministratorsPictureGetMessageAPI(string Token, int page, int limit)
        {
            var count = web_info.FindBySql("select * from web_info").Count;
            var start = (page - 1) * limit;
            var sql = "select * from web_info  limit " + start + "," + limit;
            var PictureList = web_info.FindBySql(sql);
            return Json(ResultHelper.GetAdministratorsPictureMessageModel(PictureList, count), JsonRequestBehavior.AllowGet);
        }
        public ActionResult AdministratorsPictureGetPlaceAPI()
        {
            var list = web_dictionaries.FindBySql("select * from web_dictionaries where Kind=1");
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        public ActionResult AdministratorsPictureMessageAPI(long Id)
        {
            var list = web_info.FindById(Id);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        
        public ActionResult AdministratorsPictureGetDetailAPI(int Id)
        {
            var Place = web_info.FindById(Id).Place;
            var dictionariesId = web_dictionaries.FindBySql("select * from web_dictionaries where Place='" + Place + "'")[0].Id;
            var list = web_dictionaries.FindBySql("select * from web_dictionaries where Kind="+(dictionariesId * 100 + 1));
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        public ActionResult AdministratorsPictureGetDetailAPI2(long Id)
        {
            
            var list = web_dictionaries.FindBySql("select * from web_dictionaries where Kind=" + (Id * 100 + 1));
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        public ActionResult AdministratorsPictureSaveAPI(long Id, string Place, string Detail, string PicUrl)
        {
            if(Place==""|| Detail == ""|| PicUrl == "")
                return Json(ResultHelper.GetErrorModel("请填写完毕后再保存"), JsonRequestBehavior.AllowGet);
            if(Id==0)
            {
                var List = new web_info();
                List.Place = Place;
                List.Detail = Detail;
                List.PicUrl = PicUrl;
                List.Createtime = DateTime.Now;
                List.Updatetime = DateTime.Now;
                List.Save();
            }
            else
            {
                var List = web_info.FindById(Id);
                List.Place = Place;
                List.Detail = Detail;
                List.PicUrl = PicUrl;
                List.Updatetime = DateTime.Now;
                List.Save();
            }
            
            return Json(ResultHelper.GetSuccessModel("保存成功"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult AdministratorsAgriculturalGetMessageAPI(string Token, int page, int limit)
        {
            var count = product_info.FindBySql("select * from product_info").Count;
            var start = (page - 1) * limit;
            var sql = "select * from product_info  limit " + start + "," + limit;
            var AgriculturalList = product_info.FindBySql(sql);
            return Json(ResultHelper.GetAdministratorsAgriculturalMessageModel(AgriculturalList, count), JsonRequestBehavior.AllowGet);
        }
        public ActionResult AdministratorsAgriculturalGetDetailAPI(long Id)
        {
            var list = product_info.FindById(Id);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        public ActionResult UploadFile()
        {
            try
            {
                var file = Request.Files[0]; //获取选中文件    
                var filecombin = file.FileName.Split('.');
                if (file == null || String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0 || filecombin.Length < 2)
                {
                    return Json(new
                    {
                        code = 0,
                        msg = "上传失败",
                        data = ""
                    });
                }
                //定义本地路径位置  
                string local = "Content\\image";
                string filePathName = string.Empty;
                string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, local);

                var tmpName = Server.MapPath("~/Content/image");
                var tmp = file.FileName;
                var tmpIndex = 0;
                //判断是否存在相同文件名的文件 相同累加1继续判断  
                while (System.IO.File.Exists(tmpName + tmp))
                {
                    tmp = filecombin[0] + "_" + ++tmpIndex + "." + filecombin[1];
                }

                //不带路径的最终文件名  
                filePathName = tmp;

                if (!System.IO.Directory.Exists(localPath))
                    System.IO.Directory.CreateDirectory(localPath);
                string localURL = Path.Combine(local, filePathName);
                file.SaveAs(Path.Combine(localPath, filePathName));   //保存图片（文件夹）  
                return Json(new
                {
                    code = 0,
                    msg = "上传成功",
                    data = ""
                });
            }
            catch { }
            return Json(new
            {
                src = "",
                name = "",   // 获取文件名不含后缀名  
                msg = "上传出错"
            });
        }
        /// <summary>
        /// 调用API之前验证Token是否有效
        /// </summary>
        /// <param name="Token"></param>
        /// <returns></returns>
        public bool Verification(string Token)
        {
            if (Token == null)
            {
                return false;
            }
            else
            {
                var result = user_token.Find(p => p.Token == Token);
                if (result.Count == 0)
                {
                    return false;
                }
                else
                {
                    if (result[0].Expirytime < DateTime.Now)
                        return false;
                    else
                        return true;
                }
            }
        }
    }
}